<?php

namespace app\common\command;

use addons\shopro\service\Wallet as WalletService;
use app\admin\model\market\Acceleration;
use app\admin\model\user\Prizelog;
use app\common\model\User;
use app\common\model\Userchildren;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\exception\HttpResponseException;

class Rebatemoney extends Command
{
    protected function configure()
    {
        $this->setName('rebatemoney')->setHelp('砸金蛋返利')->setDescription('砸金蛋返利');
    }

    protected function execute(Input $input, Output $output)
    {
        $prizeLogModel = new Prizelog();
        $data          = $prizeLogModel->with(['prize'])->where('prize_id','>',5)->where('status', '<', 2)->select();
        if ($data) {
            $user_data = [];
            Db::startTrans();
            try {
                foreach ($data as $k => $v) {
                    if (!$v->prize) {
                        $v->status = 2;
                    } else {
                        $userInfo = User::where(['id' => $v->user_id])->find();
                        if ($userInfo) {
                                //质押
                                $user_money     = $v->prize->num;
                                $v->status      = 1;
                                $all_has_return = bcadd($v->has_return, $user_money);
                                if ($all_has_return > $v->prize->money) {
                                    $user_money = $v->prize->money - $v->has_return;
                                    $v->status  = 2;
                                }
                                if (isset($user_data[$v->user_id])) {
                                    $user_data[$v->user_id]['user_money'] += $user_money;
                                } else {
                                    $user_data[$v->user_id]['user_money'] = $user_money;
                                }
                            $v->has_return = $user_money;
                            if ($user_money > 0) {
                                WalletService::change($v->user_id, 'score', $user_money, 'prize', $v->id,
                                    '抽中'.$v->prize->title.'奖品返利');
                            }
                        } else {
                            $v->status = 2;
                        }
                    }
                    $v->save();
                }
                //计算团队质押业绩
                if ($user_data) {
//                    $this->team_zhiya($user_data);
                    $this->pingji_zhiya($user_data);
                }
                echo '执行成功';
                Db::commit();
            } catch (HttpResponseException $e) {
                Db::rollback();
                $data    = $e->getResponse()->getData();
                $message = $data ? ($data['msg'] ?? '') : $e->getMessage();
                echo $message;
//                format_log_error($e, 'Rebatemoney.HttpResponseException', $message);
            }
        }
    }

    /**
     * @menu 质押分成
     * @Author:男人的坏
     * @Date:2024-07-20 10:43
     */

    public function team_zhiya($data)
    {
        foreach ($data as $k => $v) {
            $user_ids = Userchildren::where(['children_id' => $k])->column('member_id');
            if ($user_ids) {
                $user_data = User::with(['acceleration'])->whereIn('id', $user_ids)->where('level', '>',
                    0)->field('id,level')->select();
                if ($user_data) {
                    foreach ($user_data as $key => $val) {
                        if ($val->acceleration) {
                            $parent_user_money = bcmul($val->acceleration->rizhiya, $v['user_money'], 2) / 100;
                            if ($parent_user_money > 0) {
                                $userInfo = User::where(['id' => $val->id])->find();
                                if ($userInfo) {
                                    WalletService::change($val->id, 'score', $parent_user_money, 'team_rzy', [],
                                        '团队日质押奖励');
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    public function pingji_zhiya($data)
    {
        foreach ($data as $k => $v) {
            $user_ids = Userchildren::where(['children_id' => $k])->order('level',
                'asc')->column('member_id');
            if ($user_ids) {
                $currMemberLevel = User::where(['id' => $k])->value('level');
                $this->dailifenhong($user_ids, $v['user_money'], $currMemberLevel);
            }
        }
    }

    public function dailifenhong(
        $members,
        $team_amount,
        $currMemberLevel
    ) {
        $flatLevelUsed = false; // 标记平级是否已经使用过
        $ping_bili     = 0;
        foreach ($members as $v) {
            $currentAgent = \app\common\model\User::where(['id' => $v])->where('level', '>', 0)->find();
            if ($currentAgent) {
                if ($currentAgent->level > $currMemberLevel) {
                    $currentCommissionLevelRule = getCommissionLevelRule($currentAgent->level);
                    if ($currentCommissionLevelRule) {
                        //级差奖励
//                        $rizhiya = Acceleration::where('id','<',$currentAgent->level)->order('id desc')->value('rizhiya');
                        if (!$ping_bili) {
                            $ping_bili = $currentCommissionLevelRule->rizhiya;
//                             $currentCommissionLevelRule->rizhiya -= $rizhiya;
                        } else {
                            $currentCommissionLevelRule->rizhiya -= $ping_bili;
                            $ping_bili                           += $currentCommissionLevelRule->rizhiya;
                        }
                        $commission = caculateGoodsCommission($currentCommissionLevelRule, $team_amount, 'rizhiya');
                        if ($commission > 0) {
                            $currCommissionReward = $commission;

                            if ($currCommissionReward > 0) {
                                WalletService::change($v, 'score', $currCommissionReward, 'jicha_team_rzy', [],
                                    '级差日质押奖励');
                                $flatLevelUsed = false;
                            }
                        }
                    }
                    $currMemberLevel = $currentAgent->level;
                } elseif ($currentAgent->level == $currMemberLevel && !$flatLevelUsed) {
                    //平级奖规则
                    $currentCommissionLevelRule = getCommissionLevelRule($currentAgent->level);
                    if ($currentCommissionLevelRule) {
                        $commission = caculateGoodsCommission($currentCommissionLevelRule, $team_amount,
                            'parallel_rizhiya_scale');
                        if ($commission > 0) {
                            $currCommissionReward = $commission;
                            if ($currCommissionReward > 0) {
                                $flatLevelUsed = true;
                                WalletService::change($v, 'score', $currCommissionReward, 'pingji_team_rzy', [],
                                    '平级日质押奖励');
                            }
                        }
                    }
                }
            }
        }
    }
}
